//
//  DMSelectPayWayVC.m
//  DistributionMall
//
//  Created by JHnoplan on 2018/10/16.
//  Copyright © 2018年 JHnoplan. All rights reserved.
//

#import "DMSelectPayWayVC.h"
#import "DMSucceedVC.h"

//model
#import "KPaymentTypeModel.h"
#import "KWxPayModel.h"

//request
#import "KPaymentRequest.h"

//other
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "WXApiManager.h"

@interface DMSelectPayWayVC ()<WXApiDelegate,WXApiManagerDelegate>
{
    NSInteger flag;//支付方式 1微信2支付宝
}
@property (weak, nonatomic) IBOutlet UILabel *priceLb;
@property (weak, nonatomic) IBOutlet UIImageView *wxImage;
@property (weak, nonatomic) IBOutlet UIImageView *alImage;



@end

@implementation DMSelectPayWayVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addObserver];
    self.priceLb.text = [NSString stringWithFormat:@"¥%.2f",self.payPrice];
    [self startInit];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [WXApiManager sharedManager].delegate = self;
    
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [WXApiManager sharedManager].delegate = nil;
}


-(void)startInit {
    self.navigationItem.title = @"订单支付";
    self.view.backgroundColor = DMDefaultColor;
    flag = 2;//默认微信支付
}

- (IBAction)buttonClick:(UIButton *)sender {
    if (sender.tag == 1) {
        //微信
        flag = 2;
        _wxImage.image = [UIImage imageNamed:@"Select"];
        _alImage.image = [UIImage imageNamed:@"noselet"];
    }else if (sender.tag == 2) {
        //支付宝
        flag = 1;
        _wxImage.image = [UIImage imageNamed:@"noselet"];
        _alImage.image = [UIImage imageNamed:@"Select"];
    }else if (sender.tag == 3) {
        //支付
        //根据订单号支付
        KPaymentRequest * request = [[KPaymentRequest alloc]initPaymentWithAmount:nil bizType:@"2" entityid:self.entityid type:@(flag).stringValue recommendCod:@""];
        [JLProgressHUDManager showLoadingHud];
        MJWeakSelf
        [request newStartRequestWithCompletion:^(KBaseModel *baseModel) {
            
            [JLProgressHUDManager hideHud];
            //调起支付宝支付
            if (flag == 1) {
                [weakSelf pickUpAlipayWithSignedStr:baseModel.data];
                
            }else if (flag == 2){
                //调起微信支付
                
                [weakSelf handleWx:baseModel];
            }
            
        } failure:^(KBaseModel *errorModel) {
            
            
            [JLProgressHUDManager showErrorHud:errorModel.msg];
            
        }];
        
    }
}

#pragma mark ----other----

-(void)addObserver{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAliPayCallback:) name:KAliPayNotiName object:nil];
}

/**
 调起支付宝支付
 */
- (void)pickUpAlipayWithSignedStr:(NSString *)signedStr
{
    NSString *appScheme = @"com.DistributionMallAPPJ";
    MJWeakSelf
    [[AlipaySDK defaultService] payOrder:signedStr fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        NSInteger code = [resultDic[@"resultStatus"] integerValue];
        if (9000 == code) {
            //更新用户信息
            [[KuserInfo shareInstance] updateUserModel:^(KUserModel *userModel) {
                
            } failure:^{
                
            }];
            
            if (weakSelf.paySuccessBlock) {
                weakSelf.paySuccessBlock();
                
            }
            DMSucceedVC * vc = [[DMSucceedVC alloc]init];
            vc.typeIndex = paySucceed;
            [weakSelf.navigationController pushViewController:vc animated:YES];
            
        }else if (8000 == code){
            [JLProgressHUDManager showErrorHud:@"支付失败！"];
        }else if (4000 == code){
            [JLProgressHUDManager showErrorHud:@"支付失败！"];
        }else if (6001 == code){
            [JLProgressHUDManager showErrorHud:@"支付失败！"];
        }else if (6002 == code){
            [JLProgressHUDManager showErrorHud:@"支付失败！"];
        }else if (6004 == code){
            [JLProgressHUDManager showErrorHud:@"支付失败！"];
        }else{
            [JLProgressHUDManager showErrorHud:@"支付失败！"];
        }
    }];
}

-(void)handleAliPayCallback:(NSNotification*) notification{
    NSInteger code = [notification.object[@"resultStatus"] integerValue];
    
    if (9000 == code) {
        //更新用户信息
        [[KuserInfo shareInstance] updateUserModel:^(KUserModel *userModel) {
            
        } failure:^{
            
        }];
        
        if (self.paySuccessBlock) {
            self.paySuccessBlock();
            
        }

        DMSucceedVC * vc = [[DMSucceedVC alloc]init];
        vc.typeIndex = paySucceed;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (8000 == code){
        [JLProgressHUDManager showErrorHud:@"支付失败！"];
    }else if (4000 == code){
        [JLProgressHUDManager showErrorHud:@"支付失败！"];
    }else if (6001 == code){
        [JLProgressHUDManager showErrorHud:@"支付失败！"];
    }else if (6002 == code){
        [JLProgressHUDManager showErrorHud:@"支付失败！"];
    }else if (6004 == code){
        [JLProgressHUDManager showErrorHud:@"支付失败！"];
    }else{
        [JLProgressHUDManager showErrorHud:@"支付失败！"];
    }
    
}

// 处理微信支付
- (void)handleWx:(KBaseModel *)baseModel
{
    KWxPayModel *model = [KWxPayModel modelWithJSON:baseModel.data];
    [self wechatPay:model];
}

/// 调起微信支付
- (void)wechatPay:(KWxPayModel *)paymodel{
    PayReq *request = [[PayReq alloc] init];
    request.partnerId = paymodel.partnerid;
    request.prepayId = paymodel.prepayid;
    request.package = paymodel.package;
    request.nonceStr = paymodel.noncestr;
    request.timeStamp = [paymodel.timeStamp unsignedIntValue];
    request.sign = paymodel.sign;
    [WXApi sendReq:request];
}

/**
 微信支付结果回调
 */
- (void)managerDidRecvPayResponse:(PayResp *)resp{
    switch (resp.errCode) {
        case WXSuccess:
        {
            [self verifyWxPaymentResult];
        }
            break;
        case WXErrCodeUserCancel:{
            [JLProgressHUDManager showErrorHud:@"支付失败！"];
            
        }
            break;
        default:
            break;
    }
}

/// 微信支付结果
- (void)verifyWxPaymentResult{
    //更新用户信息
    [[KuserInfo shareInstance] updateUserModel:^(KUserModel *userModel) {
        
    } failure:^{
        
    }];

    if (self.paySuccessBlock) {
        self.paySuccessBlock();
    }
    
    DMSucceedVC * vc = [[DMSucceedVC alloc]init];
    vc.typeIndex = paySucceed;
    [self.navigationController pushViewController:vc animated:YES];
}




@end
